import os
from django.conf import settings
from django.shortcuts import render
from django.contrib.admin.views.decorators import staff_member_required
from django.views.generic import View
from django.views.decorators.http import require_GET,require_POST
from apps.articles.models import ArticleCategory,Article
from utils import restful
from .forms import EditArticleCategoryForm,AddArticleForm,EditArticleForm

@staff_member_required(login_url='index')
def index(request):
    return render(request,'cms/index.html')

class AddArticleView(View):

    def get(self,request):
        categories = ArticleCategory.objects.all()
        context = {
            'categories': categories
        }
        return render(request,'cms/add_article.html', context=context)

    def post(self,request):
        form = AddArticleForm(request.POST)
        if form.is_valid():
            title = form.cleaned_data.get('title')
            desc = form.cleaned_data.get('desc')
            thumbnail = form.cleaned_data.get('thumbnail')
            content = form.cleaned_data.get('content')
            category_id = form.cleaned_data.get('category')
            try:
                category = ArticleCategory.objects.get(pk=category_id)
            except Exception as e:
                return restful.params_error(message='没有这个分类！')
            Article.objects.create(title=title,desc=desc,thumbnail=thumbnail,content=content,category=category,author=request.user)
            return restful.ok()
        else:
            return restful.params_error(message=form.get_error())

class EditArticleView(View):
    def get(self,request):
        referer = request.META['HTTP_REFERER']
        article_id = request.GET.get('article_id')
        article = Article.objects.select_related('category').get(pk=article_id)
        context = {
            'referer': referer,
            'article': article,
            'categories': ArticleCategory.objects.all()
        }
        return render(request,'cms/add_article.html',context=context)

    def post(self,request):
        form = EditArticleForm(request.POST)
        if form.is_valid():
            title = form.cleaned_data.get('title')
            desc = form.cleaned_data.get('desc')
            thumbnail = form.cleaned_data.get('thumbnail')
            content = form.cleaned_data.get('content')
            category_id = form.cleaned_data.get('category')
            article_id = form.cleaned_data.get('article_id')
            category = ArticleCategory.objects.get(pk=category_id)
            Article.objects.filter(pk=article_id).update(title=title,desc=desc,thumbnail=thumbnail,content=content,category=category)
            return restful.ok()
        else:
            return restful.params_error(message=form.get_error())

@require_POST
def delete_article(request):
    try:
        article_id = request.POST.get('article_id')
    except:
        return restful.params_error(message='没有找到这篇文章！')
    Article.objects.filter(pk=article_id).update(is_delete=True)
    return restful.ok()

@require_GET
def article_category(request):
    categories = ArticleCategory.objects.all()
    context = {
        'categories': categories
    }
    return render(request,'cms/article_category.html',context=context)

@require_POST
def add_article_category(request):
    name = request.POST.get('name')
    if len(name) >= 10:
        return restful.params_error(message='分类名长度不超过10位！')
    if ArticleCategory.objects.filter(name=name).exists():
        return restful.params_error(message='分类名重复！')
    ArticleCategory.objects.create(name=name)
    return restful.ok()

@require_POST
def edit_article_category(request):
    form = EditArticleCategoryForm(request.POST)
    if form.is_valid():
        pk = form.cleaned_data.get('pk')
        name = form.cleaned_data.get('name')
        if ArticleCategory.objects.filter(name=name).exists():
            return restful.params_error(message='分类名重复！')
        try:
            ArticleCategory.objects.filter(pk=pk).update(name=name)
            return restful.ok()
        except Exception as e:
            return restful.params_error(message='没有这个分类')
    else:
        return restful.params_error(message=form.get_error())

@require_POST
def delete_article_category(request):
    pk = request.POST.get('pk')
    if not pk:
        return restful.params_error(message='请输入分类pk！')
    try:
        ArticleCategory.objects.filter(pk=pk).delete()
        return restful.ok()
    except Exception as e:
        return restful.params_error(message='没有这个分类！')

@require_POST
def upload_file(request):
    file = request.FILES.get('file')
    name = file.name
    with open(os.path.join(settings.MEDIA_ROOT,name), 'wb') as fp:
        for chunk in file.chunks():
            fp.write(chunk)
    url = request.build_absolute_uri(settings.MEDIA_URL)
    return restful.result(data={'url':url+name})